package com.zyz.M_File和IO流.IO流.节点流.InputStream和OutputStream;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author: vick
 * @Date: 2025/4/8
 * @Description:
 * @version: 1.0
 */
public class FileCopy {
    public static void main(String[] args) {
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;

        try {
            //1. 创建File对象
            /*
            //非文本文件=》成功
            File source = new File("source.jpg");
            File copy = new File("copy.jpg");*/
            //文本文件==》成功！
            File source = new File("hello.txt");
            File copy = new File("hello-copy.txt");

            //2. 创建流对象
            fileInputStream = new FileInputStream(source);
            fileOutputStream = new FileOutputStream(copy);

            //3. 复制操作 （读写）
            byte[] buffer = new byte[1024];
            //每次读入到 buffer中的字节数
            int len;
            while ((len = fileInputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭资源
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
